package com.example.demo.xss;

import com.example.demo.utils.common.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 防止XSS攻击的过滤器
 */
public class XssFilter implements Filter
{
    /**
     * 排除链接
     */
    public List<String> excludes = new ArrayList<>();

    /**
     * xss过滤开关
     */
    public boolean enabled = false;

    /** 过滤写入操作 */
    private static List<String> MATCH_WORD = new ArrayList<>();
    static {
        MATCH_WORD.add("SAVE");
        MATCH_WORD.add("UPDATE");
        MATCH_WORD.add("INSERT");
        MATCH_WORD.add("SET");
    }

    @Override
    public void init(FilterConfig filterConfig)
    {
        /** 获取排除路径 */
        String tempExcludes = filterConfig.getInitParameter("excludes");
        /** 获取开关 */
        String tempEnabled = filterConfig.getInitParameter("enabled");
        if (StringUtils.isNotEmpty(tempExcludes))
        {
            String[] url = tempExcludes.split(",");
            for (int i = 0; url != null && i < url.length; i++)
            {
                excludes.add(url[i]);
            }
        }
        if (StringUtils.isNotEmpty(tempEnabled))
        {
            enabled = Boolean.valueOf(tempEnabled);
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException
    {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        /** 拦截的路径或不是写入操作，直接返回 */
        if (handleExcludeURL(req, resp) || !isWriteIn(req))
        {
            chain.doFilter(request, response);
            return;
        }
        /** 过滤请求中的参数 */
        XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
        chain.doFilter(xssRequest, response);
    }

    /** 校验路径是否被排除 */
    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response)
    {
        if (!enabled)
        {
            return true;
        }
        if (excludes == null || excludes.isEmpty())
        {
            return false;
        }
        String url = request.getServletPath();
        for (String pattern : excludes)
        {
            Pattern p = Pattern.compile("^" + pattern);
            Matcher m = p.matcher(url);
            if (m.find())
            {
                return true;
            }
        }
        return false;
    }

    /** 路径关键词过滤 */
    private boolean isWriteIn(HttpServletRequest request) {
        String url = request.getServletPath().toUpperCase();
        return MATCH_WORD.stream().anyMatch(w -> url.contains(w));
    }

    @Override
    public void destroy()
    {

    }
}